package com.hsck.order.kds.base.isnoam.network

import com.hjq.toast.Toaster
import com.hsck.order.kds.base.isnoam.log.XLog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.withContext
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.concurrent.CancellationException

open class BaseRepository {

    private val job = Job()
    private val scope = CoroutineScope(Dispatchers.IO + job)

    suspend fun <T> safeApiCall(
        apiCall: suspend () -> BaseResp<T>,
    ): ResultWrapper<T?> {
        return try {
            // 使用自定义协程作用域进行 API 调用
            val response = withContext(scope.coroutineContext) {
                apiCall.invoke()
            }
            if (response.code == 200) {
                ResultWrapper(isSuccess = true, data = response.data, total = response.total)
            } else {
                when (response.code) {
                    300 -> {
                        Toaster.show(response.msg)
                        ResultWrapper(isSuccess = false, isRefresh = true)
                    }
                    401 -> {
                        ResultWrapper(isSuccess = false, isLogin = true)
                    }
                    else -> {
                        Toaster.show(response.msg)
                        ResultWrapper(isSuccess = false, error = Exception(response.msg))
                    }
                }
            }
        } catch (throwable: Throwable) {
            // 捕获网络异常
            when (throwable) {
                is SocketTimeoutException -> {
                    Toaster.show("请求超时异常")
                }
                is UnknownHostException,
                is ConnectException -> {
                    Toaster.show("网络异常，请检查您的网络连接")
                }
                is CancellationException -> {
                    // 捕获协程取消异常，不抛出
                    XLog.e("协程被取消")
                }
                else -> {
                    if (throwable.message != "StandaloneCoroutine was cancelled") {
                        Toaster.show(throwable.message)
                    }
                }
            }
            XLog.e("ResultWrapper Throwable ：${throwable.message}")
            ResultWrapper(isSuccess = false, error = throwable)
        }
    }

    // 确保在不再需要时手动取消协程作用域
    fun onCleared() {
        job.cancel() // 手动取消协程作用域
    }
}
